<!--
 * @Description:
 * @Author: 
 * @Date: 2023-08-16 09:20:58
 * @LastEditor: 
 * @LastEditTime: 2023-09-12 14:33:45
 
-->


<template>
	<view class="VideoPay" :class="{ active: show }" @click="$emit('close')">
		<view class="popup" @click.stop="">
			<view class="p_head">
				<view class="left">
					<text class="text1">请支持本站，解锁后继续观看</text>
				</view>
				<view class="right" :style="'color:'+isColor" @click="$emit('close')">关闭</view>
			</view>
			<!--<view class="p_text">
				<view class="left">
					<text class="text1">解锁本集：</text>
					<text class="text2" :style="'color:'+isColor">{{ price }}{{richtext.jfname}}</text>
				</view>
			
				<view class="right">账号余额：{{ userInfoStore.usable || 0 }}{{richtext.jfname}}</view>
			</view>-->
			<scroll-view scroll-y="true" style="height:640rpx">
			<view class="p_list">
				<!-- <view class="item">
					<view class="content">
						<view class="line1">
							<text class="text1">69.9</text>
							<text class="text2">元</text>
						</view>
						<view class="line2">
							<text class="text1">6900</text>
							<text class="text2">+2500积分</text>
						</view>
					</view>
					<view class="tips">多送30元</view>
					<view class="badge">特惠</view>
				</view> -->
				<!-- <view class="item item2">
					<view class="content">
						<view class="line1">
							<text class="text1">69.9</text>
							<text class="text2">元</text>
						</view>
						<view class="line2">
							<text class="text1">解锁整部剧</text>
							<text class="text2"></text>
						</view>
					</view>
				</view> -->
				
				<view class="item" v-if="iosIsPay" v-for="(item, index) in integralData" :key="index" @click="recharge('integral', item.id, item.price,item.type_text
)">
					<view class="content">
						<view class="line1">
							<text class="text1">{{ item.price }}</text>
							<text class="text2">元</text>
						</view>
						<view class="line2">
							<text class="text1">{{ item.original_usable }}</text>
							<text class="text2" v-if="item.give_usable">+{{ item.give_usable }}</text>
							<text class="text2">{{richtext.jfname}}</text>
						</view>
					</view>
					<view class="badge" v-if="item.flag">{{ item.flag }}</view>
				</view>
				<view class="item" v-if="iosIsPay" v-for="(item, index) in vipData" :key="index" @click="recharge('member', item.id, item.price,item.type_text
)">
					<view class="content">
						<view class="line1">
							<text class="text1">{{ item.price }}/{{ item.type_text }}</text>
						</view>
						<view class="line2">
							<text class="text2">全站爽剧免费看</text>
						</view>
					</view>
					<view class="tips">开通会员</view>
				</view>
			
				<!--<view class="item item2" :style="'background:'+isColor" @click="gotoPage('/pages/user/integral/task')">
					<view class="content">
						<view class="line1">
							<text class="text1">免费{{richtext.jfname}}</text>
						</view>
						<view class="line2">
							<text class="text1">做任务获取{{richtext.jfname}}</text>
						</view>
					</view>
				</view>-->
				<!-- #ifdef MP-WEIXIN -->
				<view class="item item2" :style="'background:'+isColor" v-if="token && ad" @click="$emit('showAd'), $emit('close')">
					<view class="content">
						<view class="line1">
							<text class="text1">每日任务</text>
						</view>
						<view class="line2">
							<text class="text1">看视频获取{{richtext.jfname}}</text>
						</view>
					</view>
				</view>
				<!-- #endif -->
				
				
			<!---	<view class="item item2" :style="'background:'+isColor" @click="jumpView('/pages/user/info/contact')">
					<view class="content">
						<view class="line1">
							<text class="text1">联系我们</text>
						</view>
					</view>
				</view>-->
			</view>
			</scroll-view>
			<!--<view class="p_info">虚拟商品购买后不可退换，青少年请在家长陪同下充值</view>-->
		</view>
	</view>
</template>

<script>
	import { mapState, mapGetters, mapMutations, mapActions } from "vuex"
	export default {
		name: "VideoPay",
		props: {
			show: {
				type: Boolean,
				default: false
			},
			price: {
				type: Number,
				default: 0
			},
			ad: {
				type: Boolean,
				default: false
			}
		},
		data() {
			return {
				juji:"20",
				userInfoStore: this.$store.state.user.userInfo,
				integralData: [],
				vipData: [],
				buttonLoading: true,
				isAdLoading: false,
				isColor:getApp().globalData.isColor,
				timer:null
			};
		},
		onUnload() {
				//console.log("子组件页面销毁")
			clearInterval(this.timer); 
			this.timer=null
		},
		beforeUnmount() {
					// clearTime
					//console.log("能否关闭")
					clearInterval(this.timer);
					this.timer=null
				},
		onHide() {
				//console.log("子组件隐藏")
			clearInterval(this.timer); 
			this.timer=null
		},
		computed: {
			...mapGetters("user", ["token", "userInfo"]),
			...mapGetters("app", ["iosIsPay", "config","richtext"]),
		},
		watch: {
			userInfo: {
				deep: true,
				handler: function(newValue, oldValue) {
					this.userInfoStore = newValue
				}
			},
			show(newValue, oldValue) {
				if(newValue) {
					this.token && this.getUserInfo()
				}
			},
		},
		created() {
			this.isColor=getApp().globalData.isColor,
			
			this.getIntegralList()
			this.getVipList()
			
		},
		methods: {
			...mapActions('user', ['getUserInfo']),
			gotoPage(url) {
				if(!this.token) {
					this.$u.toast('请先登录!')
					setTimeout(()=>{
						uni.redirectTo({
							url: '/pages/login/login'
						});
					},1000)
					
				}
				// #ifdef MP-WEIXIN
				if(!this.iosIsPay) return this.jumpView('/pages/user/info/contact')
				// #endif
				this.jumpView(url)
			},
			// 获取积分套餐列表
			getIntegralList() {
				this.$request('integral.list').then(res => {
					if(res.code === 1) {
						res.data.list && res.data.list.length && (this.integralData = res.data.list)
					}
				})
			},
			// 获取vip套装列表
			getVipList() {
				this.$request('user.vip').then(res => {
					if(res.code === 1) {
						res.data.list && res.data.list.length && (this.vipData = res.data.list)
					}
				})
			},
			// 充值
			recharge(type, id, price,name) {
				if(!this.token) {
				this.$u.toast('请先登录!')	
				setTimeout(()=>{
					uni.redirectTo({
						url: '/pages/login/login'
					});
				},2000)
				}else{
					//console.log(type,id,price,name)
					const data = {};
					data.id=id
					data.price=price,
					data.name=name
					uni.setStorageSync('dataKey', data);
					uni.navigateTo({
						url:'/pages/common/channel'
					})
				}
				
			},
			xGetPay(order_sn,payment,platform){
				uni.login({
					provider: 'weixin',
					success: success => {
						if(success.errMsg === 'login:ok') {
							
							this.$request('common.xunipay', {
								order_sn,
								payment,
								platform,
								code: success.code
							}).then(res => {
								//console.log(res)
								if(res.code === 1) {
									if(platform == 'H5') {
										const div = document.createElement('divpay');
										div.innerHTML = res.data.pay_data;
										document.body.appendChild(div);
									} else {
										this.xunipay(res.data.pay_data)
									}
								}
							})
							
						}
					}
				})
			},
			//非虚拟支付调起
			getPay(order_sn,payment,platform){
				this.$request('common.pay', {
					order_sn,
					payment,
					platform,
				}).then(res => {
					//console.log(res)
					if(res.code === 1) {
						if(platform == 'H5') {
							//const div = document.createElement('divpay');
							//div.innerHTML = res.data.pay_data;
							//document.body.appendChild(div);
							//console.log("获取到跳转链接",res.data.pay_data)
								window.open(res.data.pay_data)
								//window.location.href=res.data.pay_data
								const self=this
								this.timer = setInterval(function(){
								   self.orderStatus(order_sn);
								}, 2000);
								
						} else {
							this.pay(res.data.pay_data)
						}
					}
				})
			},
			orderStatus(order_sn){
				this.$request('common.status', {
					order_sn
				}).then(res => {
					//console.log("订单状态",res)
					if(res.data==1){
						clearInterval(this.timer); 
						this.timer=null
						uni.showToast({
						    title: '支付成功',
							icon: 'none',
							duration: 2000
						});
						this.buttonLoading = true
						this.getUserInfo()
						this.$emit('close')
						// uni.$emit('updateUserInfo', true)
						uni.hideLoading()
					}
					
				})
			},
			// 获取支付参数
			callPay(order_sn, payment, platform) {
				// #ifdef MP-TOUTIAO
					var that = this
						this.$request('common.dypay', {
							order_sn,
							payment,
							platform,
						}).then(res => {
							//console.log(res)
							if(res.code === 1) {
								
								if(platform == 'H5') {
									const div = document.createElement('divpay');
									div.innerHTML = res.data.pay_data;
									document.body.appendChild(div);
								} else {
									//console.log('进入当前')
									tt.requestOrder({
									   data: res.data.data, // 请勿在前端对data做任何处理
									   byteAuthorization: res.data.byteAuthorization, // 请勿在前端对byteAuthorization做任何处理
									   success: (res) => {
									     //console.log('成功', res);
										tt.getOrderPayment({
										 orderId:res.orderId,
										 success: (res) => {
											uni.showToast({
												  title: '支付成功',
												icon: 'none',
												duration: 2000
											  });
											that.buttonLoading = true
											that.getUserInfo()
											uni.$emit('updateUserInfo', true)
											uni.hideLoading()
										 },
										 fail: (res) => {
										  uni.showToast({
										  		     title: '当前用户的客户端版本不支持小程序虚拟支付',
										  		 	icon: 'none',
										  		 	duration: 2000
										  		 });
										  		that.buttonLoading = true
										  		uni.hideLoading()
										   
										 },
										});
									   },
									   fail: (res) => {
									   
									   that.buttonLoading = true
									   uni.hideLoading()
									     uni.showToast({
									     	title:res,
									     	icon: 'none',
									     	duration: 2000
									     })
										 
									   },
									 });
									// tt.pay({
									//   orderInfo: {
									//     order_id:  res.data.pay_data.data.order_id ,
									//     order_token:res.data.pay_data.data.order_token ,
									//   },
									//   service: 5,
									//   success(res) {
									// 	  //console.log(res,'success')
									//     if (res.code == 0) {
									// 		uni.showToast({
									// 		      title: '支付成功',
									// 		  	icon: 'none',
									// 		  	duration: 2000
									// 		  });
									// 		that.buttonLoading = true
									// 		that.getUserInfo()
									// 		uni.$emit('updateUserInfo', true)
									// 		uni.hideLoading()
											
									//       // 支付成功处理逻辑，只有res.code=0时，才表示支付成功
									//       // 但是最终状态要以商户后端结果为准
									//     }else{
									// 		uni.showToast({
									// 		     title: '当前用户的客户端版本不支持小程序虚拟支付',
									// 		 	icon: 'none',
									// 		 	duration: 2000
									// 		 });
									// 		this.buttonLoading = true
									// 		uni.hideLoading()
									// 	}
									//   },
									//   fail(res) {
									// 	 uni.showToast({
									// 	      title: '当前用户的客户端版本不支持小程序虚拟支付',
									// 	  	icon: 'none',
									// 	  	duration: 2000
									// 	  });
									// 	 this.buttonLoading = true
									// 	 uni.hideLoading()
									//     // 调起收银台失败处理逻辑
									//   },
									// });
								}
							}
						})
				
				// #endif
				// #ifndef MP-TOUTIAO
				this.$request('common.ifxunipay').then(res=>{
					if(res.data.xunipay_switch == 0){
						this.getPay(order_sn,payment,platform)
					}else{
						// #ifdef MP-WEIXIN
						var iosd = wx.getSystemInfoSync()
						if(this.iosIsPay && iosd.platform == 'ios'){
							this.getPay(order_sn,payment,platform)
							
						}else{
							this.xGetPay(order_sn,payment,platform)
							
						}
					// #endif
					// #ifndef MP-WEIXIN
					
						this.getPay(order_sn,payment,platform)
						
					// #endif
					}
				})
				// #endif
				
			},
			// 发起 小程序/公众号 支付
			xunipay(pay){
				var that = this
				// #ifdef MP-WEIXIN
				const SDKVersion = wx.getSystemInfoSync().SDKVersion
				
				if (this.compareVersion(SDKVersion, '2.19.2') >= 0 || wx.canIUse('requestVirtualPayment')) {
				  wx.requestVirtualPayment({
				    signData: JSON.stringify({
				      offerId: pay.signData.offerId,
				      buyQuantity: pay.signData.buyQuantity,
				      env: pay.signData.env,
				      currencyType: pay.signData.currencyType,
				      platform: pay.signData.platform,
				      productId: pay.signData.productId,
				      goodsPrice: pay.signData.goodsPrice,
				      outTradeNo: pay.signData.outTradeNo,
				      attach: pay.signData.attach,
				    }),
				    paySig: pay.paySig, 
				    signature: pay.signature,
				    mode: pay.mode,
				    success(res) {
				      ////console.log('requestVirtualPayment success', res)
					uni.showToast({
					      title: '支付成功',
					  	icon: 'none',
					  	duration: 2000
					  });
					that.buttonLoading = true
					that.getUserInfo()
					that.$emit('close')
					// uni.$emit('updateUserInfo', true)
					uni.hideLoading()
					
				    },
				    fail({ errMsg, errCode }) {
				      ////console.error(errMsg, errCode)
					  uni.showToast({
					      title: '支付失败',
					  	icon: 'none',
					  	duration: 2000
					  });
					that.buttonLoading = true
					uni.hideLoading()
				    },
				  })
				} else {
				  ////console.log('当前用户的客户端版本不支持 wx.requestVirtualPayment')
				  
				  uni.showToast({
				      title: '当前用户的客户端版本不支持小程序虚拟支付',
				  	icon: 'none',
				  	duration: 2000
				  });
				 this.buttonLoading = true
				 uni.hideLoading()
				  
				}
				// #endif
				
				// // #ifdef H5
				
				// WeixinJSBridge.invoke(
				// 	'getBrandWCPayRequest', {
				// 		"appId": pay.appId, // 公众号ID，由商户传入     
				// 		"timeStamp": pay.timeStamp, // 时间戳，自1970年以来的秒数     
				// 		"nonceStr": pay.nonceStr, // 随机串     
				// 		"package": pay.package, // 订单详情扩展字符串
				// 		"signType": pay.signType, // 微信签名方式：     
				// 		"paySign": pay.paySign // 微信签名 
				// 	},
				// 	res => {
				// 		if (res.err_msg == "get_brand_wcpay_request:ok") {
				// 			uni.showToast({
				// 			    title: '支付成功',
				// 				icon: 'none',
				// 				duration: 2000
				// 			});
				// 			this.buttonLoading = true
				// 			this.getUserInfo()
				// 			uni.$emit('updateUserInfo', true)
				// 			uni.hideLoading()
				// 		} else {
				// 			uni.showToast({
				// 			    title: '支付失败',
				// 				icon: 'none',
				// 				duration: 2000
				// 			});
				// 			this.buttonLoading = true
				// 			uni.hideLoading()
				// 		}
				// 	});
				// // #endif
				
				// // #ifdef APP-PLUS
				// // APP
				// 	uni.getProvider({
				// 		service: "payment",
				// 		success: e => {
				// 			const type = e.provider.includes('wxpay')
				// 			type && uni.requestPayment({
				// 				"provider": "wxpay",
				// 				"orderInfo": pay,
				// 				success: success => {
				// 					uni.showToast({
				// 						title: '支付成功',
				// 						icon: 'none',
				// 						duration: 2000
				// 					});
								
				// 					this.buttonLoading = true
				// 					this.getUserInfo()
				// 					uni.$emit('updateUserInfo', true)
				// 					uni.hideLoading()
				// 				},
				// 				fail: fail => {
				// 					if(fail.errCode === -8) {
				// 						uni.showToast({
				// 							title: '未安装微信客户端',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 						this.buttonLoading = true
				// 						uni.hideLoading()
				// 					} else {
				// 						uni.showToast({
				// 							title: '支付失败',
				// 							icon: 'none',
				// 							duration: 2000
				// 						});
				// 						this.buttonLoading = true
				// 						uni.hideLoading()
				// 					}
				// 				}
				// 			})
				// 		},
				// 		fail: e => {
				// 			this.payFail("获取iap支付通道失败")
				// 		}
				// 	});
				// // #endif
			},
			pay(pay) {
						// #ifdef MP-WEIXIN
						uni.requestPayment({
							timeStamp: pay.timeStamp,
							nonceStr: pay.nonceStr,
							package: pay.package,
							signType: pay.signType,
							paySign: pay.paySign,
							success: success => {
								uni.showToast({
								    title: '支付成功',
									icon: 'none',
									duration: 2000
								});
								this.buttonLoading = true
								this.getUserInfo()
								that.$emit('close')
								// uni.$emit('updateUserInfo', true)
								uni.hideLoading()
							},
							fail: fail => {
								uni.showToast({
								    title: '支付失败',
									icon: 'none',
									duration: 2000
								});
								this.buttonLoading = true
								uni.hideLoading()
							}
						})
						// #endif
						
						// #ifdef H5
						WeixinJSBridge.invoke(
							'getBrandWCPayRequest', {
								"appId": pay.appId, // 公众号ID，由商户传入     
								"timeStamp": pay.timeStamp, // 时间戳，自1970年以来的秒数     
								"nonceStr": pay.nonceStr, // 随机串     
								"package": pay.package, // 订单详情扩展字符串
								"signType": pay.signType, // 微信签名方式：     
								"paySign": pay.paySign // 微信签名 
							},
							res => {
								if (res.err_msg == "get_brand_wcpay_request:ok") {
									uni.showToast({
									    title: '支付成功',
										icon: 'none',
										duration: 2000
									});
									this.buttonLoading = true
									this.getUserInfo()
									uni.$emit('updateUserInfo', true)
									uni.hideLoading()
								} else {
									uni.showToast({
									    title: '支付失败',
										icon: 'none',
										duration: 2000
									});
									this.buttonLoading = true
									uni.hideLoading()
								}
							});
						// #endif
						// #ifdef APP-PLUS
						// APP
							uni.getProvider({
								service: "payment",
								success: e => {
									const type = e.provider.includes('wxpay')
									type && uni.requestPayment({
										"provider": "wxpay",
										"orderInfo": pay,
										success: success => {
											uni.showToast({
												title: '支付成功',
												icon: 'none',
												duration: 2000
											});
										
											this.buttonLoading = true
											this.getUserInfo()
											uni.$emit('updateUserInfo', true)
											uni.hideLoading()
										},
										fail: fail => {
											if(fail.errCode === -8) {
												uni.showToast({
													title: '未安装微信客户端',
													icon: 'none',
													duration: 2000
												});
												this.buttonLoading = true
												uni.hideLoading()
											} else {
												uni.showToast({
													title: '支付失败',
													icon: 'none',
													duration: 2000
												});
												this.buttonLoading = true
												uni.hideLoading()
											}
										}
									})
								},
								fail: e => {
									this.payFail("获取iap支付通道失败")
								}
							});
						// #endif
					
				
			},
			//判断微信js版本用
			compareVersion(_v1, _v2) {
			  if (typeof _v1 !== 'string' || typeof _v2 !== 'string') return 0
			
			  const v1 = _v1.split('.')
			  const v2 = _v2.split('.')
			  const len = Math.max(v1.length, v2.length)
			
			  while (v1.length < len) {
			    v1.push('0')
			  }
			  while (v2.length < len) {
			    v2.push('0')
			  }
			
			  for (let i = 0; i < len; i++) {
			    const num1 = parseInt(v1[i], 10)
			    const num2 = parseInt(v2[i], 10)
			
			    if (num1 > num2) {
			      return 1
			    } else if (num1 < num2) {
			      return -1
			    }
			  }
			
			  return 0
			},
		}
	}
</script>

<style lang="scss" scoped>
	.VideoPay {
		width: 100%;
		height: 100%;
		position: absolute;
		bottom: -100%;
		left: 0;
		z-index: 100;
		transition: all 0.5s;
		
		&.active {
			bottom: 0;
		}
		
		.popup {
			width: 100%;
			min-height: 60%;
			background: #000;
			border-radius: 20rpx 20rpx 0 0;
			position: absolute;
			bottom: 0;
			left: 0;
			z-index: 1;
			color: #fff;
			padding: 0 40rpx 60rpx 40rpx;
			border-top: 2rpx solid #333;
			display: flex;
			flex-direction: column;
			
			.p_head {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				position: relative;
				padding: 30rpx 0;
				font-size: 32rpx;
				
				.left {
					flex: 1;
					display: flex;
					flex-direction: row;
					
					.text1 {
						font-weight: 700;
						line-height: 48rpx;
					}
					
					.text2 {
						font-size: 24rpx;
						color: rgba(#fff, 0.5);
						margin: 0 40rpx;
						white-space: nowrap;
						line-height: 48rpx;
					}
				}
				
				.right {
					color: #EE7F33;
					white-space: nowrap;
					margin-left: 20rpx;
				}
			}
			
			.p_text {
				display: flex;
				flex-direction: row;
				justify-content: space-between;
				align-items: center;
				font-size: 28rpx;
				
				.left {
					display: flex;
					flex-direction: row;
					align-items: center;
					
					.text2 {
						color: #EE7F33;
					}
				}
				
				.right {
					color: rgba(#fff, 0.7);
				}
			}
			
			.p_list {
				flex: 1;
				margin-top: 40rpx;
				display: flex;
				flex-wrap: wrap;
				align-content: flex-start;
				
				.item {
					width: calc((100% - 40rpx) / 2);
					height: 168rpx;
					border-radius: 20rpx;
					background: #fff;
					margin-bottom: 40rpx;
					position: relative;
					overflow: hidden;
					color: #000;
					display: flex;
					flex-direction: column;
					
					&:nth-child(2n) {
						margin-left: 40rpx;
					}
					
					&.item2 {
						background: #EE7F33;
						color: #fff;
					}
					
					.content {
						flex: 1;
						display: flex;
						flex-direction: column;
						justify-content: center;
						// align-items: center;
						
						.line1 {
							display: flex;
							flex-direction: row;
							align-items: flex-end;
							justify-content: center;
							
							.text1 {
								font-size: 40rpx;
								font-weight: 700;
							}
							
							.text2 {
								font-size: 28rpx;
							}
						}
						.line3 {
							display: flex;
							flex-direction: column;
							align-items: center;
							justify-content: center;
							
							.text1 {
								font-size: 40rpx;
								font-weight: 700;
							}
							
							.text2 {
								font-size: 28rpx;
							}
						}
						.line2 {
							font-size: 28rpx;
							display: flex;
							flex-direction: row;
							align-items: center;
							justify-content: center;
							
							.text2 {
								color: #EE7F33;
							}
						}
					}
					
					.tips {
						font-size: 28rpx;
						text-align: center;
						background: #EE7F33;
						padding: 8rpx 0;
						color: #fff;
					}
					
					.badge {
						position: absolute;
						top: -2rpx;
						right: -2rpx;
						padding: 4rpx 16rpx;
						font-size: 24rpx;
						background: #EE7F33;
						border-radius: 0 0 0 20rpx;
						color: #fff;
					}
				}
			}
			
			.p_info {
				font-size: 24rpx;
				text-align: center;
				margin-top: 20rpx;
			}
		}
	}
</style>